//
//  PersonInfoAuthenVC.m
//  HxgProject
//
//  Created by hxg on 2018/3/7.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "PersonInfoAuthenVC.h"
#import "PersonInfoCell.h"

#import "HXPhotoView.h"
#import "HXPhotoPicker.h"
#import "UIViewController+HXExtension.h"

#import "TTPhotoPickerController.h"
#import "RDVTabBarController.h"

#import "AuthenService.h"
#import "PersonInfo.h"
#import "UIButton+Extention.h"
#import <IQKeyboardReturnKeyHandler.h>

@interface PersonInfoAuthenVC ()<UITableViewDelegate,UITableViewDataSource,HXAlbumListViewControllerDelegate,UIImagePickerControllerDelegate,UIScrollViewDelegate,UITextFieldDelegate>
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
}

@property (nonatomic, strong) UITableView *personInfoTableView;

// 配置数据源
@property (nonatomic, strong) NSMutableArray *personDataSource;

@property (nonatomic, strong) HXPhotoManager *manager;

// 照片是否上传的标记
@property (nonatomic, assign) BOOL isZhengMianUpLoad;
@property (nonatomic, assign) BOOL isFanMianUpLoad;
@property (nonatomic, assign) BOOL isAllMianUpLoad;


@end

@implementation PersonInfoAuthenVC


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    [super viewWillDisappear:animated];
}

-(HXPhotoManager *)manager
{
    if (!_manager)
    {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isZhengMianUpLoad = NO;
    self.isFanMianUpLoad = NO;
    self.isAllMianUpLoad = NO;
    
    [self setUpUI];
    
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                                                style:UIBarButtonItemStyleDone
                                                               target:self
                                                               action:@selector(submitAction:)];
    
    self.navigationItem.rightBarButtonItem = btnItem;
    
    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
    
}

- (void)setUpUI
{
    self.navigationItem.title = @"个人信息认证";
    
    [self.view addSubview:self.personInfoTableView];
    [self.personInfoTableView registerClass:[PersonInfoCell class]
                 forCellReuseIdentifier:@"PersonCell"];
    [self.personInfoTableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height));
    }];
}

-(UITableView *)personInfoTableView
{
    if (!_personInfoTableView)
    {
        _personInfoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, kScreen_Width, kScreen_Height - 44.0f) style:UITableViewStyleGrouped];
        
        _personInfoTableView.delegate = self;
        _personInfoTableView.dataSource = self;
        _personInfoTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
        _personInfoTableView.tableFooterView = [[UIView alloc] init];
        _personInfoTableView.showsVerticalScrollIndicator = NO;
    }
    
    return _personInfoTableView;
}


#pragma mark - tableViewDelegate

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return 0;
    }
    
    return 0.01f;//section头部高度
}
//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return [[UIView alloc] init];
    }
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    static NSString *identifier = @"PersonCell";
    
    PersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell)
    {
        cell = [[PersonInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0) {
            cell.autherContentField.text = self.showPerson.name;
        } else if (indexPath.row == 1) {
            cell.autherContentField.text = self.showPerson.school;
        }else if (indexPath.row == 2) {
            cell.autherContentField.text = self.showPerson.education;
        }else if (indexPath.row == 3) {
            cell.autherContentField.text = self.showPerson.schoolAddr;
        }else if (indexPath.row == 4) {
            cell.autherContentField.text = self.showPerson.qq;
        }else if (indexPath.row == 5) {
            cell.autherContentField.text = self.showPerson.webchat;
        }else if (indexPath.row == 6) {
            cell.autherContentField.text = self.showPerson.bankAccount;
        }else if (indexPath.row == 7) {
            cell.autherContentField.text = self.showPerson.bank;
        }else if (indexPath.row == 8) {
            cell.autherContentField.text = self.showPerson.subBank;
        }else if (indexPath.row == 9) {
            
            if (isEmptyString(self.showPerson.chsiAcc))
            {
                cell.autherContentField.text = [[NSUserDefaults standardUserDefaults]
                                                objectForKey:[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]];
            }
            else
            {
                cell.autherContentField.text = self.showPerson.chsiAcc;
            }
        }else if (indexPath.row == 10) {
            [cell.autherContentField setSecureTextEntry:YES];
            if (isEmptyString(self.showPerson.chsiPwd))
            {
                cell.autherContentField.text = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_PWD",[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]]];
            }
            else
            {
                cell.autherContentField.text = self.showPerson.chsiPwd;
            }
        }
        
        cell.autherContentField.delegate = self;
        cell.autherContentField.tag = indexPath.row;
        [cell.autherContentField addTarget:self
                                    action:@selector(getInputVal:)
                          forControlEvents:UIControlEventEditingChanged];
        
        cell.autherNameLbl.text = [self.personDataSource objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }
    else if(1 == indexPath.section)
    {
        cell.autherNameLbl.text = @"身份证号";
        cell.autherContentField.text = self.showPerson.idCard;
        cell.autherContentField.delegate = self;
        cell.autherContentField.tag = indexPath.section * 20 + indexPath.row;
        [cell.autherContentField addTarget:self
                                    action:@selector(getInputVal:)
                          forControlEvents:UIControlEventEditingChanged];
        return cell;
    }

    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 1)
    {
        return 1;
    }
    
    return self.personDataSource.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - all Actions

- (void)getInputVal:(UITextField *)field
{
    switch (field.tag) {
        case 0:
            self.showPerson.name = field.text;
            NSLog(@"self.personInfo.name==>%@ === %@",self.showPerson.name,field.text);
            
            break;
        case 1:
            self.showPerson.school = field.text;
            NSLog(@"school==>%@",self.showPerson.school);

            break;
        case 2:
            self.showPerson.education = field.text;
            NSLog(@"education==>%@",self.showPerson.education);

            break;
        case 3:
            self.showPerson.schoolAddr = field.text;
            break;
        case 4:
            self.showPerson.qq = field.text;
            break;
            
        case 5:
            self.showPerson.webchat = field.text;
            break;
        case 6:
            self.showPerson.bankAccount = field.text;
            break;
        case 7:
            self.showPerson.bank = field.text;
            break;
        case 8:
            self.showPerson.subBank = field.text;
            break;
        case 9:
                self.showPerson.chsiAcc = field.text;
                 [[NSUserDefaults standardUserDefaults] setObject:field.text
                                                           forKey:[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]];
            NSLog(@"self.showPerson.chsiAcc===%@",self.showPerson.chsiAcc);
            break;
        case 10:
                self.showPerson.chsiPwd = field.text;
                [[NSUserDefaults standardUserDefaults] setObject:field.text
                                                          forKey:[NSString stringWithFormat:@"%@_PWD",[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]]];
            
            NSLog(@"self.showPerson.chsiPwd===%@",self.showPerson.chsiPwd);
            
            break;
        case 20:
            self.showPerson.idCard = field.text;
            NSLog(@"self.showPerson.idCard:%@",self.showPerson.idCard);
            
            [[NSUserDefaults standardUserDefaults] setObject:field.text forKey:kXueXinPsw];
            
            break;
        default:
            break;
    }
}

- (void)picSelect:(UIButton *)btn
{
    __weak PersonInfoAuthenVC *weakSelf = self;
    TTPhotoPickerController * vc = [[TTPhotoPickerController alloc] initWithComplete:^(NSArray *images) {
        //选择照片之后的回调  images为选择的图片数组
        //下面代码为 示例
        NSLog(@"images==>%@",images);
        
        if ([images[0] isKindOfClass:[NSNull class]])
        {
            [SVProgressHUD showErrorWithStatus:@"所选的为截图,非相册图片,请先保存截图到相册,再选择!"];
            [SVProgressHUD dismissWithDelay:2.0f];
            return ;
        }
        
        if (btn.tag == 10)
        {
            // images[0]
            weakSelf.showPerson.frontImg = @"";
            
            weakSelf.isZhengMianUpLoad = YES;
        }
        else if(btn.tag == 11)
        {
            weakSelf.showPerson.flankImg = @"";
            weakSelf.isFanMianUpLoad = YES;
        }
        else if(btn.tag == 12)
        {
            weakSelf.showPerson.bodyImg = @"";
            weakSelf.isAllMianUpLoad = YES;
        }
        [weakSelf.personInfoTableView reloadData];

    }];
    //设置最大选择量为3张，如果不设置则默认为6张
    vc.maxPhotoNum = 1;
    vc.navigationBar.barTintColor = [UIColor whiteColor];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)submitAction:(UIButton *)btn
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes])
    {
        [SVProgressHUD showErrorWithStatus:@"您已认证过,请勿重复提交!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    if (nil != [[NSUserDefaults standardUserDefaults] objectForKey:[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]])
    {
        self.showPerson.chsiAcc = [[NSUserDefaults standardUserDefaults] objectForKey:[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]];
    }
    
    if (nil != [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_PWD",[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]]])
    {
        self.showPerson.chsiPwd = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_PWD",[[NSUserDefaults standardUserDefaults] objectForKey:kPhoneNum]]];
    }
    
    
    // 新增非空判断
    if (isEmptyString(self.showPerson.name)
        || isEmptyString(self.showPerson.school)
        || isEmptyString(self.showPerson.education)
        || isEmptyString(self.showPerson.schoolAddr)
        || isEmptyString(self.showPerson.qq)
        || isEmptyString(self.showPerson.webchat)
        || isEmptyString(self.showPerson.idCard)
        || isEmptyString(self.showPerson.bankAccount)
        || isEmptyString(self.showPerson.bank)
        || isEmptyString(self.showPerson.subBank)
        || isEmptyString(self.showPerson.chsiAcc)
        || isEmptyString(self.showPerson.chsiPwd))
    {
        [SVProgressHUD showErrorWithStatus:@"内容不能为空!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在请求.."];
    __weak PersonInfoAuthenVC *weakSelf = self;
    AuthenService *authenService = [[AuthenService alloc] init];
    [authenService setUserInfoWithPerson:self.showPerson
                            withCallBack:^(BOOL isSuccess) {
                                [SVProgressHUD dismiss];
                                if (isSuccess)
                                {
                                    [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                            forKey:kPersonInfoAuthenRes];
                                    [SVProgressHUD showSuccessWithStatus:@"操作成功!"];
                                    [SVProgressHUD dismissWithDelay:2.0f];
                                    [weakSelf.navigationController popViewControllerAnimated:YES];
                                }
                                else
                                {
                                    [[NSUserDefaults standardUserDefaults] setBool:NO
                                                                            forKey:kPersonInfoAuthenRes];
                                    [SVProgressHUD showErrorWithStatus:@"操作失败!"];
                                    [SVProgressHUD dismissWithDelay:2.0f];
                                }
                            }];
}


-(NSMutableArray *)personDataSource
{
    if (!_personDataSource)
    {
        _personDataSource = [NSMutableArray arrayWithObjects:@"真实姓名",@"学校",@"学历(本科/专科,年级)",@"学校地址(具体到宿舍门牌号)",@"QQ号码",@"微信号码",@"银行卡号(转账使用)",@"银行",@"分行",@"学信网帐号", @"学信网密码",nil];
    }
    return _personDataSource;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes])
    {
        return NO;
    }
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
